package com.hulbox.app;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.util.Log;

public class MyJSON {
	private static final String TAG = "Myinstaller";
	public MainActivity parent = null;
	
	public JSONObject getJSONfrom(String url){

		//initialize
		InputStream is = null;
		String result = "";
		JSONObject jArray = null;

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		}catch(Exception e){
			Log.e(TAG, "Error in http connection(1) "+e.toString());
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			Log.e(TAG, "Error converting result(1) "+e.toString());
		}

		//try parse the string to a JSON object
		try{
			jArray = new JSONObject(result);
		}catch(JSONException e){
			Log.e(TAG, "Error parsing data(1) "+e.toString());
		}

		return jArray;
	}

	ArrayList<HashMap<String, String>> itemArray = new ArrayList<HashMap<String, String>>();
	HashMap<String, String> item = new HashMap<String, String>();
	public boolean parseJSON(String url) {
		/*
		 * 데이터 초기화
		 */
		item.clear();
		itemArray.clear();

		/*
		 * JSON 파일 읽어오기
		 */
		JSONObject json = getJSONfrom(url);


		/*
		 * item 항목 가져오기
		 */
		try{
			final String item_ids[] = { "resultCode", "resultMsg", "topPromotionVer", "title", "arrayType1", "arrayType2", "totalItem" };
			JSONObject i1 = json.getJSONObject("item");
			if(i1 != null) {
				for(int i=0;i<item_ids.length;i++) {
					item.put(item_ids[i], i1.getString(item_ids[i]));
				}
			} else {
				Log.e(TAG, "Error parsing item data(1).");
				return false;
			}
		}catch(JSONException e) {
			Log.e(TAG, "Error parsing item data(1) "+e.toString());
		}

		/*
		 * TODO: item.resultCode 를 검사한다.
		 */

		try {    
			/*
			 * itemArray ���� �����´�. 
			 */
			final String item_ids2[] = { "idx", "appNum", "packageName", "imgUrl", "title", "comment", "adultYn", "loginYn", "limittime" };
			JSONArray  itemarray = json.getJSONArray("itemArray");

			for(int i=0;i < itemarray.length();i++){                        
				HashMap<String, String> map = new HashMap<String, String>();
				JSONObject e = itemarray.getJSONObject(i);

				for(int j = 0; j < item_ids2.length; j++) {
					map.put(item_ids2[j], e.getString(item_ids2[j]));
				}
				itemArray.add(map);
				
				boolean bImgSave = urlDownloadtoFile(map.get("imgUrl"), map.get("title") + ".png");
				if(bImgSave) {
					Log.i(TAG, "succeed download image " + map.get("imgUrl"));
				} else {
					Log.i(TAG, "failed download image " + map.get("imgUrl"));
				}
			}
		}catch(JSONException e) {
			Log.e(TAG, "Error parsing data "+e.toString());
		}
		
		//parent.setItemAdapter(itemArray);
		return true;
	}
	
    protected boolean urlDownloadtoFile(String url, String filename) {
    	HttpClient http = new DefaultHttpClient();
    	HttpGet request = new HttpGet(url);
    	
    	try {
    	    HttpResponse response = http.execute(request);
    	    InputStream fileStream = response.getEntity().getContent();
    	    FileOutputStream output = parent.openFileOutput(filename, Activity.MODE_WORLD_READABLE);

    	    byte[] buffer = new byte[1024];
    	    int len = 0;
    	    while ((len = fileStream.read(buffer)) > 0) {
    	        output.write(buffer, 0, len);
    	    }
    	    fileStream.close();
    	    output.close();
    	    return true;

    	} catch (ClientProtocolException e) {
    		//Toast.makeText( null , e.getMessage(), Toast.LENGTH_SHORT).show();
    	    e.printStackTrace();
    	} catch (IOException e) {
    		//Toast.makeText( null , e.getMessage(), Toast.LENGTH_SHORT).show();
    	    e.printStackTrace();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
    	return false;
    }
    	
}

